package com.dev.warehouse.bus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dev.warehouse.bus.entity.Goods;
import com.dev.warehouse.bus.entity.Sales;
import com.dev.warehouse.bus.entity.Salesback;
import com.dev.warehouse.bus.mapper.GoodsMapper;
import com.dev.warehouse.bus.mapper.SalesMapper;
import com.dev.warehouse.bus.mapper.SalesbackMapper;
import com.dev.warehouse.bus.service.ISalesbackService;
import com.dev.warehouse.sys.common.Constast;
import com.dev.warehouse.sys.common.ResultObj;
import com.dev.warehouse.sys.common.WebUtils;
import com.dev.warehouse.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 出库退货
 */
@Service
public class SalesbackServiceImpl extends ServiceImpl<SalesbackMapper, Salesback> implements ISalesbackService {

    @Autowired
    private SalesMapper salesMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * @param id     出库单ID
     * @param number 退货数量
     * @param remark 备注
     */
    @Override
    public synchronized ResultObj addSalesback(Integer id, Integer number, String remark) {
        //1.通过出库单ID查询出出库单信息
        Sales sales = salesMapper.selectById(id);

        //2.根据物品ID查询物品信息
        Goods goods = goodsMapper.selectById(sales.getGoodsid());
        if (sales.getNumber() - number < 0) {
            //如果数量小于0
            return ResultObj.BACKINPORT_ERROR_WEAK;
        }
        //修改入库的数量
        sales.setNumber(sales.getNumber() - number);
        //修改物品的数量     物品的数量+出仓退货的数量
        goods.setNumber(goods.getNumber() + number);
        salesMapper.updateById(sales);
        //4.进行修改
        goodsMapper.updateById(goods);
        //5.添加退货单信息
        Salesback salesback = new Salesback();
        salesback.setGoodsid(sales.getGoodsid());

        salesback.setNumber(number);
        User user = (User) WebUtils.getSession().getAttribute("user");
        salesback.setOperateperson(user.getName());


        salesback.setSalebackprice(sales.getSaleprice());
        salesback.setPaytype(sales.getPaytype());

        salesback.setSalesbacktime(new Date());
        salesback.setRemark(remark);


        salesback.setCustomerid(sales.getCustomerid());


        getBaseMapper().insert(salesback);
        return ResultObj.BACKINPORT_SUCCESS;
    }

}
